#include <conio.h>
#include "POLYGON.H"
#include "INPUT.H"

int main()
{	
	MouseState mouseState;
	char ch;
	boolean mouseOn;
	byte numButtons;
	int row = 0;
	int col = 0;
	int tInput;
	int position;
	int i,j;
	byte color = 0;
	Polygon car;
	boolean found = loadPolygon("CAR.PLY", &car);
	if(!found){
		exit(EXIT_FAILURE);
	}
	setMode(VGA_MODE);
	mouseOn = initMouse(&numButtons);	
	if(mouseOn){
		mouseState = getMouseState();
		showMouseCursor();
		boundMouseVertical(0,80);
	}
	while(TRUE){
		if(mouseOn){
			mouseState = getMouseState();
			if(mouseState.y < 80 && (mouseState.y % 10)!= 0 && (mouseState.y % 10)!= 9 ){
				row = mouseState.y/10;
			}			
			if((mouseState.x % 10)!= 0 && (mouseState.x % 10)!= 9){
				col = mouseState.x/10;
			}
			
		}
		if(kbhit()){
			tInput = getKey();
			/* Escape to quit*/
			if(tInput == 27){
				break;
			}
			
			if(!mouseOn){
				switch (tInput) {
					case 328 :
						row--;
						if(row < 0){
							row+=8;
						}
						break;
					case 331 :
						col--;
						if(col < 0){
							col+=32;
						}
						break;
					case 333 :
						col++;
						if(col >=32){
							col-=32;
						}
						break;
					case 336 :
						row++;
						if(row >= 8){
							row-=8;
						}
						break;
				}
			}		
		}
		position--;
		if(position < 0){
			position += SCREEN_WIDTH;
		}
		setBackground(LIGHT_BLUE);
		color = 0;
		for(j=0;j<8;j++){
			for(i=0;i<32;i++){
				fillRectangle(10*i+1,10*j+1,10*i+8,10*j+8,color);
				color++;
			}
		}
		drawRectangle(10*col,10*row,10*col+9,10*row+9,BLACK);
		color = (row<<5	)+col;
		drawPolygon(car, position, 125, color);
		redraw();		
		delay(33);
	}	
	freePolygon(&car);
	setMode(TEXT_MODE);
	return EXIT_SUCCESS;
}